/* eslint-disable react/require-default-props */
import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import { Icon, Upload, Modal, message } from 'antd';
import ImageGallery from 'react-image-gallery';
import { uploadToQiniu } from '@/utils/qiniuUpload';
import 'react-image-gallery/styles/css/image-gallery.css';
import './index.less';

export default class UploadImage extends PureComponent {
  static propTypes = {
    showUploadBtn: PropTypes.bool,
    showRemoveIcon: PropTypes.bool,
    previewVisible: PropTypes.bool,
    previewList: PropTypes.array,
    startIndex: PropTypes.number,
    max: PropTypes.number,
    size: PropTypes.oneOf(['small']),
    isInProgress: PropTypes.func, // isInProgress => {}
  };

  static defaultProps = {
    showUploadBtn: true,
    showRemoveIcon: true,
    previewVisible: false,
    previewList: [],
    startIndex: 0,
    max: Infinity,
    size: undefined,
  };

  constructor(props) {
    super(props);
    if (props.isInProgress) {
      props.isInProgress(this.isInProgress);
    }
    this.state = {
      inProgressTask: [],
      previewList:[]
    };
  }

  onPreview = files => {
    const { fileList } = this.props;
    const list = fileList
      .filter(item => item.url || item.response)
      .map(({ thumbUrl, response, url }) => ({
        original: url || response.url,
        thumbnail: url || response.url,
      }));

    if (!list.length) return;
    const i = list.findIndex(
      item => (files.url || (files.response && files.response.url)) === item.original
    );
    this.setState({
      previewVisible: true,
      previewList: list,
      startIndex: i,
    });
  };

  isInProgress = () => !!this.state.inProgressTask.length;

  customRequest = async event => {
    await this.setState(prev => ({
      inProgressTask: [...prev.inProgressTask, event],
    }));
    uploadToQiniu(event.file, ({ loaded, size }) => {
      event.onProgress({ percent: (loaded / size) * 100 });
    })
      .then(response => {
        event.onSuccess({ url: response });
        this.setState(prev => ({
          inProgressTask: prev.inProgressTask.filter(task => task !== event),
        }));
      })
      .catch(e => {
        event.onError(e);
        this.setState(prev => ({
          inProgressTask: prev.inProgressTask.filter(task => task !== event),
        }));
      });
  };

  beforeUpload = file => {
    const isImage = file.type.startsWith('image/');
    if (!isImage) message.error('上传文件格式有误，仅支持图片上传');
    return isImage;
  };

  handleCancel = () => this.setState({ previewVisible: false });

  render() {
    const { showRemoveIcon, showUploadBtn, max, size, ...otherProps } = this.props;
    const { previewVisible, previewList, startIndex } = this.state;
    const isOversize = this.props.fileList && this.props.fileList.length >= max;

    return (
      <div className="clearfix upload-image-cpt-wrapper">
        <Upload
          multiple
          className={classNames('upload-image-cpt', {
            hideDeleteIcon: !showRemoveIcon,
            [size]: size,
          })}
          listType="picture-card"
          beforeUpload={this.beforeUpload}
          accept="image/png,image/jpeg,image/jpg,image/gif"
          action="http://up.qiniu.com/putb64/-1"
          customRequest={this.customRequest}
          onPreview={this.onPreview}
          showUploadList={{ showRemoveIcon, showPreviewIcon: true }}
          {...otherProps}
        >
          {showUploadBtn && !isOversize && <Icon type="plus" />}
        </Upload>
        <Modal
          centered
          destroyOnClose
          footer={null}
          visible={previewVisible}
          onCancel={this.handleCancel}
          className="self-img-preview"
        >
          <ImageGallery
            items={previewList}
            startIndex={startIndex}
            showFullscreenButton={false}
            showPlayButton={false}
            showThumbnails={previewList ? previewList.length > 1 : false}
          />
        </Modal>
      </div>
    );
  }
}
